package com.springboot.jdk.nio;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel Demo2 案例
 * 从磁盘文件读取数据到Buffer里面
 *
 * @author: zr
 * @date: 2021-10-19
 */
public class FileChannelShareLockReadDemo {

    public static void main(String[] args) throws IOException {
        String path = "F:\\develop\\channel\\hello.txt";

        // 构造一个传统的文件输入流
        FileInputStream fileInputStream = new FileInputStream(path);

        // 通过文件输出流获取到对应的FileChannel, 已NIO的方式来写文件
        FileChannel channel = fileInputStream.getChannel();

        // channel.lock(0, Integer.MAX_VALUE, true);

        ByteBuffer buffer = ByteBuffer.allocateDirect(11);

        // 读数据写入buffer ，所以写完了之后，buffer 的position就是16
        channel.read(buffer);

        // 读取刚刚写入的数据，limit = 当前position = 16, position = 0
        buffer.flip();

        byte[] bytes = new byte[11];
        buffer.get(bytes);

        System.out.print(new String(bytes));

        channel.close();
        fileInputStream.close();
    }
}
